package com.chinapex.rest;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelFutureListener;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleState;

import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;

import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

public class LoggingServer {
    private static Logger _logger = LoggerFactory.getLogger(LoggingServer.class);

    @ChannelHandler.Sharable
    private static class CloseOnIdleHandler extends ChannelDuplexHandler {
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent e = (IdleStateEvent) evt;
                if (e.state() == IdleState.READER_IDLE) {
                    ctx.close();
                } else if (e.state() == IdleState.WRITER_IDLE) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);                    
                }
            }
        }
    }


    @ChannelHandler.Sharable
    private static class HttpPipelineingHandler extends ChannelInboundHandlerAdapter {
        private HttpRequest _request = null;

        public static HttpPipelineingHandler apply() {
            return new HttpPipelineingHandler();
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            if (msg instanceof HttpRequest) {
                HttpRequest request = this._request = (HttpRequest) msg;

                String uri = request.uri();

            } else if (msg instanceof HttpContent) {
                if (msg instanceof LastHttpContent) {
                    String respJsonStr = "{\"hello\":\"world\"}";
                    FullHttpResponse resp = new DefaultFullHttpResponse (
                      HttpVersion.HTTP_1_1
                    , HttpResponseStatus.OK
                    , Unpooled.copiedBuffer(respJsonStr, CharsetUtil.UTF_8)
                    );
                    resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/json; charset=UTF-8");

                    boolean keepAlive = HttpUtil.isKeepAlive(_request);
 
                    if (keepAlive) {
                        resp.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, resp.content().readableBytes());
                        resp.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
                    }
                    ctx.write(resp);
                    if (!keepAlive) {
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                    }
                }
            } else {
                _logger.warn("no valid http request: {}", msg);
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }

    }

    private static ChannelInitializer<SocketChannel> buildChannelInitializer(ChannelHandler handler) {
        return new ChannelInitializer<SocketChannel>() {
            public void initChannel(SocketChannel ch) throws Exception {
                // ch.pipeline().addLast("read_timeout", new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS));
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                // ch.pipeline().addLast("decoder_decompress", new HttpContentDecompressor());

                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                // ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
                // ch.pipeline().addLast("encoder_compress", new HttpContentCompressor());

                CorsConfig corsConfig = CorsConfigBuilder
                    .forAnyOrigin()
                    .allowNullOrigin()
                    .allowCredentials()
                    .build();
                ch.pipeline().addLast("cors", new CorsHandler(corsConfig));
                ch.pipeline().addLast("idle", new IdleStateHandler(1, 1, 0));
                ch.pipeline().addLast("idle-close", new CloseOnIdleHandler());
                ch.pipeline().addLast(handler);
            }
        };

    }

    public static void main(String[] args) throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                 .channel(NioServerSocketChannel.class)
                 .localAddress(new InetSocketAddress("127.0.0.1", 1111))
                 .childHandler(buildChannelInitializer(HttpPipelineingHandler.apply()));
        try {
            ChannelFuture f = bootstrap.bind().sync();
            _logger.info("start server at 127.0.0.1:1111");
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
